package com.lp.common.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-03-11 21:34:56
 */
public class RsaUtils {

    private static final String KEY_ALGORITHM = "RSA";


    /**
     * RSA公钥加密
     *
     * @param str 加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey ) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(
                new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @param privateKey 私钥
     * @return 明文
     *
     */
    public static String decrypt(String str, String privateKey) throws UnsupportedEncodingException,
            NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException,
            IllegalBlockSizeException, InvalidKeyException {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(
                new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        return new String(cipher.doFinal(inputByte));
    }

    public static void main(String[] args) throws Exception {
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCt8e0fz1Xz1FxSGkTzL1r4hD29ay23u0JfGByPOdZ6GgsXDGPuwnU6T7re96MIY6vJykNCoQ93uJGZPy/pcowwEtwcWZOdOZOoRS+e4FFHAnCMP4XvIDNAzsztmxLs9jZYeBWUEbo94wnVe7Wgz3DJT/wcNrTo/lUsuiwjFFDpZQIDAQAB";
        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK3x7R/PVfPUXFIaRPMvWviEPb1rLbe7Ql8YHI851noaCxcMY+7CdTpPut73owhjq8nKQ0KhD3e4kZk/L+lyjDAS3BxZk505k6hFL57gUUcCcIw/he8gM0DOzO2bEuz2Nlh4FZQRuj3jCdV7taDPcMlP/Bw2tOj+VSy6LCMUUOllAgMBAAECgYBMNhU4vLTiEgcpCc1v5y2qePY8CbuMJoWb+Ip6zlKESOjW/lzCfXyzQb+UdVd/E3xu+ymhBcQrJjjUtfSeCcwVgyBSH3Z639w2wb3i7CjJQ6wisEhHYQ2E+lLdAHNAzWCKoYMEegX0WOi2/H9Wo7HhvX2PQgvHD2XtJIA1mkheuQJBANWh75BDgF0VVGvf+kNPBdUURcpeneqWx5hKVzmo/TxHuIqvW8YYe5tBB49imurnKJBfMnoUUnxsZB/VRVcbGQMCQQDQcRDGmOVePXh5ZG2WHF1GWNk0Bqvwiy1X5CWfjXr2kD663oszTneGalGYLUO9ROBknBF8VlRluj1kbJDLOcN3AkAvWqDeqofGmlbHPrObveV+EOtTa1u3x0pg8IGbL2FKvl8iprJCG+UySdziJKpQTYMJVYC73MtX9zLOd5jSMRh/AkEAnWXDlTO/f/pLDt+XINMqXASbf33KOEngY44UGvdq8uTZeaKy2ntWJloCYzdK/5ETIOX5DjriYC7STRLuA4gK4QJAR8GUOyQpdyHAheTP/Cjx2kmQM+NU4Hk+D1abQcXz9zFcgC9hwYxqE3Yk+sRDH8DX4Pt67a47KJsA0qTCVcDAoQ==";
//        String decrypt = decrypt("Z3T9ZvBoCc2/veXswKv0VsLnOUNhtEN8EVec/JzjU+834BelysmynxZJBHltCKB9N/mzzjrazJq6KWN1lHZUXtdgbFSfPfG41LKabygpyI2BgDbHs80nff72mG5uiTLAhUZ+/CMpKx5JxnL37n0dvGrskNVzngIVzXo3MEm0caI=", privateKey);
        String admin = encrypt("123456", publicKey);
        System.out.println(admin);

    }
}
